package org.xxpay.pay.channel.witbytespay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.PayDigestUtil;
import org.xxpay.core.common.util.RandomStrUtils;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.RefundOrder;
import org.xxpay.pay.channel.BaseRefund;

import java.util.Date;

import static org.xxpay.pay.channel.witbytespay.WitbytespayUtil.getSignatureByMD5;

public class WitbytespayRefundService extends BaseRefund {
    private static final MyLog _log = MyLog.getLog(WitbytespayRefundService.class);
    String url = "https://gate.pay4.witbytes.com/api/v2/payment_refunds";
    @Override
    public String getChannelName() {
        return WitbytespayConfig.CHANNEL_NAME;
    }


    public JSONObject refund(RefundOrder refundOrder) {
        String logPrefix = getChannelName() + "订单退款";
        WitbytespayConfig witbytespayConfig = new WitbytespayConfig(getRefundParam(refundOrder));
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        String refundOrderId = refundOrder.getRefundOrderId();
        JSONObject retObj = buildRetObj();
        retObj.put("refundOrderId", refundOrderId);
        retObj.put("isSuccess", false);
        //1. 组建请求报文
        WitbytespayUtil.H5PayRefundBody reqBody = new WitbytespayUtil.H5PayRefundBody();
        reqBody.amount = String.valueOf(refundOrder.getRefundAmount());
        reqBody.merchant_id = witbytespayConfig.getMerchant_id();
        reqBody.ordercode = refundOrder.getPayOrderId();
        reqBody.timestamp = String.valueOf(System.currentTimeMillis());
        reqBody.refund_code = refundOrder.getRefundOrderId();
        String sort_str = PayDigestUtil.sortedStr(JSONObject.parseObject(reqBody.toString()));
        try {
            String sign = getSignatureByMD5(sort_str,witbytespayConfig.getSecret());
            reqBody.sign = sign;
            System.out.println("request body:\n"+reqBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String reqUrl = url;
        //3. 发送http请求，并解析返回信息
        String response = WitbytespayUtil.refundRequest(reqUrl,reqBody.toString());
        System.out.println("response:\n"+response);
        JSONObject jsonObj = JSON.parseObject(response);

        //4. 解析退款结果并更改订单状态
        if("refund_success".equals(jsonObj.getString("status"))){
            //更新支付状态并修改商户余额
            retObj.put("isSuccess", true);
            retObj.put("channelOrderNo", jsonObj.getString("ordercode"));
            commonService.payOrderService.updateStatus4Refund(refundOrder.getPayOrderId());
        }else{
            _log.info("{}返回失败", logPrefix);
            _log.info("sub_code:{},sub_msg:{}", jsonObj.getString("status"), jsonObj.getString("errMsg"));
            retObj.put("channelErrCode", jsonObj.getString("status"));
            retObj.put("channelErrMsg", jsonObj.getString("errMsg"));
        }
        return retObj;

    }
    public static void main(String[] args) throws Exception {

//        String appid = "10037e6f6a4e6da4016a670fd4530012";
//        String appkey = "f7a74b6c02ae4e1e94aaba311c04acf2";
//        String url = "https://test-api-open.chinaums.com/v1/netpay/refund";
//        String testUrl = "https://test-api-open.chinaums.com/v1/netpay/refund";
//
//        //1. 组建请求报文
//        String nonce = RandomStrUtils.getInstance().getRandomString();
//        String requestTime = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYYMMDDHHMMSS);
//        SaaspayUtil.H5PayRefundBody reqBody = new SaaspayUtil.H5PayRefundBody();
//        reqBody.requestTimestamp = DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS);
//        reqBody.merOrderId = "T20240321110322";
//        reqBody.mid = "898201612345678";
//        reqBody.tid = "88880001";
//        reqBody.instMid = "H5DEFAULT";
//        reqBody.refundAmount = "1";
//        System.out.println("request body:\n" + reqBody);
//
//        //2. 获取认证报文
//
//        String authorization = getAuthorization(appid, appkey, requestTime, nonce, reqBody.toString());
//        System.out.println(authorization);
//        String refundResult = refundRequest(testUrl,authorization,reqBody.toString());
//        System.out.println(refundResult);
    }
}
